package com.ztesoft.ossup.report.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ztesoft.ossup.report.dao.JdbcTemplateDao;
import com.ztesoft.ossup.report.dao.ReportColumnGroupRepo;
import com.ztesoft.ossup.report.dao.ReportColumnRepo;
import com.ztesoft.ossup.report.dao.ReportConditionEnumRepo;
import com.ztesoft.ossup.report.dao.ReportConditionRepo;
import com.ztesoft.ossup.report.dao.ReportRepository;
import com.ztesoft.ossup.report.dao.ReportSubRepo;
import com.ztesoft.ossup.report.domain.Report;
import com.ztesoft.ossup.report.domain.ReportColumn;
import com.ztesoft.ossup.report.domain.ReportColumnGroup;
import com.ztesoft.ossup.report.domain.ReportCondition;
import com.ztesoft.ossup.report.domain.ReportConditionEnum;
import com.ztesoft.ossup.report.domain.ReportSub;

@Service("columnConfService")
public class ColumnConfService extends BaseService{
	
	@Autowired
	ReportRepository reportRep;
	
	@Autowired
	JdbcTemplateDao jdbcTemplateDao;
	
	@Autowired
	ReportColumnRepo reportColumnRepo;
	
	@Autowired
	ReportConditionRepo reportConditionRepo;
	
	@Autowired
	ReportColumnGroupRepo reportColumnGroupRepo;
	
	@Autowired
	ReportSubRepo reportSubRepo;
	@Autowired
	ReportConditionEnumRepo EnumRepo;
	
	/**
	 * 取报表sql，以获取字段信息
	 * @param reportId
	 * @return
	 */
	
	public List<Map<String, Object>> getReportCols(Long reportId){
		Map retMap = null;
		List<Map<String, Object>> retList = null;
		List<Map<String, Object>> backList = new ArrayList<Map<String, Object>>();
		try{
			//查看column表中是否有数据，有的话就直接进行查询，没有的话就根据sql进行查询
			List<ReportColumn> colList = reportColumnRepo.findByReportIdOrderBySortOrderAsc(reportId);
			List<ReportCondition> colConList = reportConditionRepo.findByReportIdOrderBySortOrderAsc(reportId);
			if(colList.size()>0){
				//返回List<Map<String, Object>>类型数据
				backList = changeObjectToMap(colList,colConList);
			}else{
				Report report = reportRep.findOne(reportId);
				String sql = doSqlNoParams(report.getSql());//对sql进行处理
				retList = jdbcTemplateDao.getData(sql);		
				if (!retList.isEmpty()){
					retMap = retList.get(0);
					backList.add(retMap);
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return backList;
	}
		
	private List<Map<String, Object>> changeObjectToMap(
			List<ReportColumn> colList, List<ReportCondition> colConList) {
		List<Map<String, Object>> backList = new ArrayList<Map<String, Object>>();
		for(int i = 0;i<colList.size();i++){
			ReportColumn rc = colList.get(i);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", rc.getId());
			map.put("code", rc.getCode());
			map.put("data_type", rc.getDataType());
			map.put("format", rc.getFormat());
			map.put("is_hidden", rc.isHidden);
			map.put("link_report", rc.getLinkReport());
			map.put("name", rc.getName());
			map.put("sort_order", rc.getSortOrder());
			map.put("style", rc.getStyle());
			map.put("width", rc.getWidth());
			for(int j = 0;j<colConList.size();j++){
				ReportCondition repCon = colConList.get(j);
				if(rc.getCode().equals(repCon.getCode())){
					map.put("queryType", repCon.getComboboxType());
					map.put("conditionType", repCon.getType());
					map.put("dataSql", repCon.getDataSql());
					map.put("isCondition", "1");

				}
				
			}
			backList.add(map);
		}
		return backList;
	}

	/**
	 * deal data that is from front end
	 * @param paramList
	 * @param reportId
	 */
	@Transactional
	public void saveColAndCondition(List<Map<String, Object>> paramList,Long reportId){
		List<ReportColumn> colList = new ArrayList<ReportColumn>();
		List<ReportCondition> conditionList = new ArrayList<ReportCondition>();;
		Report report = new Report();
		report.setId(reportId);
		for (Map<String, Object> paramMap : paramList) {
			Boolean isCondition = Boolean.parseBoolean(String.valueOf(paramMap.get("isCondition")==null?"":paramMap.get("isCondition")));
			Boolean isTableCol = Boolean.parseBoolean(String.valueOf(paramMap.get("isTableCol")==null?"":paramMap.get("isTableCol")));
			ReportColumn reportColumn = new ReportColumn();
			ReportCondition reportCondition = new ReportCondition();
//			{sortOrder=1, code=CITY_CODE, name=111, type=String, isCondition=true, isTableCol=true, isHidden=, 
//			width=60, format=date, sql=, style=, queryType=, conditionType=1, cascadeCondition=, linkReport=}
			if (isCondition){
				reportCondition.setCascadeCondition((String)paramMap.get("cascadeCondition"));
				reportCondition.setCode((String)paramMap.get("code"));
				int requryType = paramMap.get("queryType").toString().equals("")?-1:Integer.parseInt((String)paramMap.get("queryType"));
				reportCondition.setComboboxType(requryType);
				reportCondition.setDataSql((String)paramMap.get("sql"));
				reportCondition.setName((String)paramMap.get("name"));
				reportCondition.setReport(report);
				reportCondition.setSortOrder(Integer.parseInt(paramMap.get("sortOrder").toString()));
				reportCondition.setType((String)paramMap.get("conditionType"));
				conditionList.add(reportCondition);
			}
			if (isTableCol){
				reportColumn.setCode((String)paramMap.get("code"));
				reportColumn.setDataType((String)paramMap.get("type"));
				reportColumn.setFormat((String)paramMap.get("format"));
				reportColumn.setIsHidden( Boolean.parseBoolean(paramMap.get("isHidden").toString())? 1 : 0);
				reportColumn.setLinkReport((String)paramMap.get("linkReport"));
				reportColumn.setName((String)paramMap.get("name"));
				reportColumn.setReport(report);
				reportColumn.setSortOrder(Integer.parseInt(paramMap.get("sortOrder").toString()));
				reportColumn.setStyle((String)paramMap.get("style"));
				reportColumn.setWidth((String)paramMap.get("width"));
				colList.add(reportColumn);
			}
		}
		try{
			reportColumnRepo.save(colList);
			reportConditionRepo.save(conditionList);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	@Transactional
	public void doColumnTable(Map<String, Object> params){
		
		String dataCols =  (String)params.get("dataCols");
		String groupField =  (String)params.get("groupField");
		String groupName = (String)params.get("groupName");
		String doType =  (String)params.get("doType");
		String reportId =  (String)params.get("reportId");
		ReportColumnGroup reportColumnGroup = new ReportColumnGroup();
		Report report = new Report();
		report.setId(Long.parseLong(reportId));
		reportColumnGroup.setReport(report);
		reportColumnGroup.setDataCols(dataCols);
		reportColumnGroup.setGroupField(groupField);
		reportColumnGroup.setGroupName(groupName);
		try{
			if (doType.equals("add")){
				reportColumnGroupRepo.save(reportColumnGroup);
			}else if (doType.equals("edit")){
				reportColumnGroupRepo.updateDataColsByGroupFieldAndReportId(dataCols, groupName,groupField, Long.parseLong(reportId));
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}	
	
	public List<ReportColumnGroup> queryGroupParam(String reportId){
		
		List<ReportColumnGroup> reportColumnGroupList = reportColumnGroupRepo.findByReportId(Long.parseLong(reportId));
		return reportColumnGroupList;
	}
	
	@Transactional
	public void removeGroupParam(String reportId,List<String> paramList){
		List<ReportColumnGroup> groupList = new ArrayList<ReportColumnGroup>();
		for (String param : paramList) {
			reportColumnGroupRepo.deleteByGroupFieldAndReportId(param, Long.parseLong(reportId));
		}
	}
	
	public String getReportCode(Long reportId){
		Report report = reportRep.findOne(reportId);
		return report.getCode();
	}
	
	public Boolean isHaveCharts(Long reportId){
		//1  yes 0 no
    	List<ReportSub> types = reportSubRepo.findAllByReportId(reportId);
		if (types.size() > 0){
			return true;
		}
    	return false;
	}

	public void deleteByReportId(Long reportId) {
		reportColumnRepo.deleteByReportId(reportId);
	}
	
	public String getConditionList(){
		List<ReportConditionEnum> listEnum = EnumRepo.queryStype();
		List<String> stypeList = new ArrayList<String>();
		for (ReportConditionEnum ConditionEnum : listEnum) {
			stypeList.add(ConditionEnum.getStype());
		}
		String retStr = "";
		for (int i = 0; i < stypeList.size(); i++) {
			retStr = retStr + "," + stypeList.get(i);
		}
		retStr = retStr.substring(1);
		return retStr;
	}
	
}
